package lyh.hnu.interceptor;

import com.alibaba.fastjson.JSON;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import lyh.hnu.common.BaseContext;
import lyh.hnu.common.R;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("拦截到请求：{}", request.getRequestURL());
        //网页端
        Long empId = (Long) request.getSession().getAttribute("employee");
        //判断登录状态，如果登录则放行
        if (empId != null) {
            BaseContext.setCurrentId(empId);
            return true;
        }
        //移动端
        Long usrId = (Long) request.getSession().getAttribute("user");
        //判断登录状态，如果登录则放行
        if (usrId != null) {
            BaseContext.setCurrentId(usrId);
            return true;
        }
        //如果未登录则以输出流的方式向客户端响应数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return false;
    }
}
